require 'fileutils'
require 'uglifier'
require 'sass'
require 'sinatra/base'

# Namespaces Pyro::Minifier.
module Pyro
  # Public: Sinatra helpers for minifying .js and .css files in /public.
  #
  # Example
  #
  #   Pyro::App.new.helpers.minify()
  module Minifier
    # Public: Minifies all .js and .css files in /public.
    #
    # Example
    #
    #   Pyro::App.new.helpers.minify()
    #
    # Overwrites original files with minified versions.
    def minify
      Dir.glob("#{settings.public_folder}/**/*{.js,.css}").each do |file|
        case File.extname(file)
        when '.js'
          IO.write(file, minify_js(file), mode: 'w')
        when '.css'
          IO.write(file, minify_css(file), mode: 'w')
        end
      end
    end

    # Public: Minifies the contents of a .css file.
    #
    # file - Path to the file to be minified.
    #
    # Example
    #
    #   minify_css('/path/to/file.css')
    #
    # Returns the minified contents of the .css file.
    def minify_css(file)
      Sass::Engine.new(File.read(file), { style: :compressed, syntax: :scss })
                  .render()
    end

    # Public: Minifies the contents of a .js file.
    #
    # file - Path to the file to be minified.
    #
    # Example
    #
    #   minify_js('/path/to/file.js')
    #
    # Returns the minified contents of the .js file.
    def minify_js(file)
      Uglifier.new.compile(File.read(file)).strip()
    end
  end
end